import { ValidateError } from '@/error/ValidateError.ts'
import { FormInstance } from 'element-plus'

export interface ValidateRule {
  required: boolean
  message: string
}

/**
 * 自定义表单参数验证，不通过抛出异常，在全局异常处理中给出提示
 * @param param
 * @param rules
 */
export const validate = (param: Record<string, unknown>, rules: Record<string, ValidateRule[]>) => {
  Object.keys(rules).forEach(key => {
    const validateRules = rules[key]
    //循环验证规则数据
    for (const validateRule of validateRules) {
      //字段必输
      if (validateRule.required && !param[key]) {
        throw new ValidateError(validateRule.message)
      }
    }
  })
}

/*表单验证，成功执行回调方法*/
export const submitForm = async (
  formEl: FormInstance | undefined,
  cb: ((...args: unknown[]) => void | Promise<void>) | undefined,
  ...args: unknown[]
) => {
  if (!formEl) return
  await formEl.validate()
  await cb?.apply(null, args)
}
